//
//  HomeTableViewController.m
//  weibo-OC
//
//  Created by diyuyma on 16/3/19.
//  Copyright © 2016年 zhangkaiyun. All rights reserved.
//

#import "HomeTableViewController.h"
#import "UserAccountViewModel.h"
#import "StatusCell.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "StatusListViewModel.h"
#import "Status.h"

static NSString * const HomeCellId = @"HomeCellId";

@interface HomeTableViewController ()
@property (nonatomic, strong)UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong)NSMutableArray *statuses;
@end

@implementation HomeTableViewController


//数据源  模型数组
- (NSMutableArray *)statuses {
    if (_statuses == nil) {
        _statuses = [[NSMutableArray alloc] init];
    }

    return _statuses;
}

- (UIActivityIndicatorView *)indicatorView {

    if (_indicatorView == nil) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.frame = CGRectMake(10, 10, 10, 10);
    }
    return _indicatorView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!self.userLogin) {
        [self.visitorLoginView setUIInfo:nil WithTitle:@"关注一些人，回这里看看有什么惊喜"];
        return;
    }
    //准备tableView
    [self prepareTableView];
    //获取网络数据
    [self loadData:nil];
}

- (void)prepareTableView {
    // 设置下拉刷新
    self.refreshControl = [[UIRefreshControl alloc] init];
     self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"努力加载中……"];
    //添加监听方法
    [self.refreshControl addTarget:self action:@selector(loadData:) forControlEvents:UIControlEventValueChanged];
    // 1.注册 cell
    [self.tableView registerClass:[StatusCell class] forCellReuseIdentifier:HomeCellId];
    //tableView 在iOS8 中自动计算行高 需要指定两个属性
    //预估行高
    self.tableView.estimatedRowHeight = 200;
    //需要指定自动计算行高
    //要使用自动计算行高 必须有一个自上而下的约束
    
    //设置分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight =  UITableViewAutomaticDimension;
    
    self.tableView.tableFooterView = self.indicatorView;
}

- (void)viewWillAppear:(BOOL)animated {
    [self loadData:nil];
}

//MARK: 加载微博首页数据


- (void)loadData:(void(^)(NSArray *array))finished {
    
    self.refreshControl.tintColor = [UIColor redColor];
    //确定since_id
    //注意 如果max_id 和 since_id同时有值 服务器不会给任何数据
    
    NSInteger since_id = 0;
    NSInteger max_id = 0;
    

    if ([self.indicatorView isAnimating]) {
        // 上拉加载更多数据
        since_id = 0;
        max_id = [self.statuses.lastObject id];
    } else {
        // 下拉加载更多数据
        max_id = 0;
        since_id = [self.statuses.lastObject id];
    }
    
    // 加载数据
     [[[StatusListViewModel alloc] init] loadData:^(NSMutableArray *array) {
         [self.refreshControl endRefreshing];
         
         if (array == nil) {
             // 请求失败
             [SVProgressHUD showErrorWithStatus:AppErrorTip];
             //加载数据失败 停止动画
             [self.indicatorView stopAnimating];
             return ;
         }
         // 一定拿到数据
         if (since_id > 0) {
             [array addObjectsFromArray:self.statuses];
             self.statuses = array;
         } else if (max_id > 0){
             //上拉加载更多
             [self.statuses addObjectsFromArray:array];
             //加载数据完成 停止动画
             [self.indicatorView stopAnimating];
         } else {
             // 首次加载
             self.statuses = array;
         }
         // 刷新表格
         [self.tableView reloadData];
     } WithSince_id:since_id WithMax_id:max_id];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.statuses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StatusCell *cell = [tableView dequeueReusableCellWithIdentifier:HomeCellId forIndexPath:indexPath];
    Status *status = self.statuses[indexPath.row];
    
    cell.status = status;
    if (indexPath.row == self.statuses.count - 1 && ![self.indicatorView isAnimating]){
        //倒数第二行 加载更多数据  并且小菊花没有转动的时候 再加载更多数据
        [self.indicatorView startAnimating];
        [self loadData:nil];
    }
    return cell;
}

- (void)demo {
    AFHTTPSessionManager *AFN = [[AFHTTPSessionManager alloc] init];
    AFN.responseSerializer.acceptableContentTypes = [AFN.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [AFN GET:@"http://www.weather.com.cn/data/sk/101010100.html" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD showErrorWithStatus:@"网络君正在睡觉"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
    
}
@end
